<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/9/3
 * Time: 12:56
 */

namespace Home\Logic;


use Admin\Logic\MoneyLogLogic;
use Common\Utils\Constants;
use Think\Exception;

class PayLogic
{
    /**
     * @param $order_number 订单编号
     * @param $money 总金额
     * @param  $type 0微信支付 1支付宝支付 2银行卡支付
     * @return int 0余额不足 1支付成功 2支付失败
     */
    public function weChatPaySuccess($order_number,$money,$type)
    {
        $where['order_number']=':order_number';
        $bind[':order_number']=$order_number;
        $recharge_order = D('RechargeOrder')->where($where)->bind($bind)->find();
        if($recharge_order){
//            if($recharge_order['state'] == 0 && is_numeric($money) && $recharge_order['money'] <= $money) {
            if($recharge_order['status'] == 0 && is_numeric($money)) {
                return $this->rechargeSuccess($recharge_order,$type);//充值成功
            }
        }
        return 2;
    }

    /**
     * @param $order array 订单
     * @param  $type 0微信支付 1支付宝支付 2银行卡支付
     * @return  int 1支付成功 2支付失败
     */
    public function rechargeSuccess($order,$type){
        $model = M();
        $model->startTrans();
        try {
            $this->rechargeIntegral($order,$model);
            //修改订单状态
            $model->table('t_recharge_order')->where(array('id'=>$order['id']))->setField('status',1);
            $model->commit();
            return 1;
        } catch (Exception $e) {
            $model->rollback();
            return 2;
        }
    }

    //充值钻石，增加用户钻石，记录资金流动
    private function rechargeIntegral($order,$model){
        $money = $order['money'] * 10;
        $model->table('t_user')->where(array('id'=>$order['user_id']))->setInc('integral',$money);
        $model->table('t_user')->where(array('id'=>$order['user_id']))->setInc('recharge',$money);
        $currentMoney = $model->table('t_user')->where(array('id'=>$order['user_id']))->getField('integral');
        $remark = '用户充值钻石';
        $moneyLogic = new MoneyLogLogic();
        $moneyLogic->saveMoneyLog($money,
            $currentMoney,
            Constants::MONEY_SOURCE_RECHARGE,
            Constants::PUT_TYPE_IN,
            $remark,$order['user_id'],Constants::MONEY_TYPE_INTEGRAL,$model);
    }

    /**
     * 添加充值记录
     * @param $money
     * @param $user_id
     * @return mixed
     */
    public function addRechargeLog($money,$user_id){
        $log['money'] = $money;
        $log['order_number'] = build_order_no();
        $log['create_time'] = time();
        $log['user_id'] = $user_id;
        $log['status'] = 0;
        $order_id = D('RechargeOrder')->add($log);
        return $order_id;
    }
}